<template>
    <!-- 主内容区域 -->
    <main class="max-w-screen-2xl mx-auto self-center p-4 flex items-center justify-center flex-col">
        <div
            class="w-full max-w-2xl p-4 bg-white border border-gray-200 rounded-lg shadow sm:p-6 md:p-8 dark:bg-gray-800 dark:border-gray-700">
            <div class="text-xl font-semibold text-center mb-2 text-gray-900 dark:text-gray-300">
                <img :src="blogSettingsStore.blogSettings.logo" class="h-14 mr-2 inline" alt="wjblog Logo" />

                <div class="text-lg font-semibold">用户注册中心</div>
            </div>
            <div class="p-4 md:p-5">
                <!-- 引入 Element Plus 表单组件，移动端设置宽度为 5/6，PC 端设置为 2/5 -->
                <el-form class="space-y-4" ref="formRef" :rules="rules" :model="registerForm" label-width="auto">
                    <el-form-item prop="avatar" label="头像">
                        <el-upload class="avatar-uploader"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            :show-file-list="false" :on-change="handleUserAvatarImg">
                            <el-avatar v-if="registerForm.avatar" :size="100" :src="registerForm.avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Avatar />
                            </el-icon>
                        </el-upload>
                    </el-form-item>

                    <el-form-item prop="username" label="用户名">
                        <el-input size="large" v-model="registerForm.username" placeholder="请输入用户名(用于账户登录，不可修改)"
                            :prefix-icon="User" clearable />
                    </el-form-item>
                    <el-form-item prop="mail" label="邮箱">
                        <el-input size="large" v-model="registerForm.mail" placeholder="请输入邮箱" :prefix-icon="Message"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="nickname" label="昵称">
                        <el-input size="large" v-model="registerForm.nickname" placeholder="请输入昵称" :prefix-icon="Sugar"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="password" label="密码">
                        <el-input size="large" type="password" v-model="registerForm.password" placeholder="请输入密码"
                            :prefix-icon="Lock" clearable show-password />
                    </el-form-item>
                    <el-form-item prop="confirmPassword" label="确认密码">
                        <el-input size="large" type="password" v-model="registerForm.confirmPassword"
                            placeholder="请确认密码" :prefix-icon="Lock" clearable show-password />
                    </el-form-item>
                    <el-form-item prop="signature" label="个性签名">
                        <el-input size="large" v-model="registerForm.signature" placeholder="请输入适合自己标签或座右铭"
                            :prefix-icon="EditPen" clearable />
                    </el-form-item>
                    <el-form-item prop="qqId" label="QQ号码">
                        <el-input size="large" v-model="registerForm.qqId" placeholder="请输入QQ号" :prefix-icon="ChatRound"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="phoneNumber" label="手机号码">
                        <el-input size="large" v-model="registerForm.phoneNumber" placeholder="请输入手机号"
                            :prefix-icon="Iphone" clearable />
                    </el-form-item>
                    <el-form-item prop="localCity" label="所在城市">
                        <el-input size="large" v-model="registerForm.localCity" placeholder="请选择自己所在城市"
                            :prefix-icon="Location" disabled clearable />

                        <el-cascader size="large" v-model="registerForm.localCityCode" :options="areaOptions" :props="cascaderProps" class="w-full"
                            @change="handleCityChange" placeholder="请选择省市区" style="margin-right: 10px ;margin-bottom: 10px; margin-top: 10px;" clearable />
                    </el-form-item>

                    <el-form-item prop="university" label="毕业院校">
                        <el-input size="large" v-model="registerForm.university" placeholder="请选择自己的毕业/在读院校"
                            :prefix-icon="School" disabled clearable />
                        <!-- 省份选择 -->
                        <el-select size="large" v-model="selectedProvince" placeholder="先选择省份" @change="handleSchoolCityChange()" class="w-full"
                            style=" margin-right: 10px ;margin-bottom: 10px; margin-top: 10px;">
                            <el-option v-for="provinceSchools in schoolList" :key="provinceSchools.province"
                                :label="provinceSchools.province" :value="provinceSchools.province" />
                        </el-select>
                        <!-- {{ selectedProvinceSchools }} -->
                        <el-autocomplete  v-model="selectedSchool" :fetch-suggestions="schoolQuerySearch"
                            :disabled="!selectedProvince" placeholder="输入学校名称，如：北京大学" clearable
                            @select="handleSchoolSelect" style=" margin-right: 10px ;margin-bottom: 10px;" class="w-full">
                            <!-- 自定义显示模板 -->
                            <template #default="{ item }">
                                <div class="school-item">
                                    <span class="name">{{ item.name }}</span>
                                    <!-- <span class="info"> --- {{ item.city }} · {{ item.type }} · {{ item.level }}</span> -->
                                </div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <!-- <el-form-item prop="university" label="毕业院校">
                        <el-input size="large" v-model="registerForm.university" placeholder="请输入自己的毕业/在读院校"
                            :prefix-icon="School" clearable />
                    </el-form-item> -->
                    <el-form-item prop="github" label="Github链接">
                        <el-input size="large" v-model="registerForm.github" placeholder="请输入自己的Github链接"
                            :prefix-icon="Link" clearable />
                    </el-form-item>
                    <el-form-item prop="gitee" label="Gitee链接">
                        <el-input size="large" v-model="registerForm.gitee" placeholder="请输入自己的Github链接"
                            :prefix-icon="Link" clearable />
                    </el-form-item>
                    <el-form-item prop="personBlog" label="我的个人博客">
                        <el-input size="large" v-model="registerForm.personBlog" placeholder="请输入自己的个人博客链接"
                            :prefix-icon="Collection" clearable />
                    </el-form-item>
                    <el-form-item prop="introduce" label="个人介绍">
                        <el-input v-model="registerForm.introduce" :autosize="{ minRows: 2, maxRows: 4 }"
                            type="textarea" placeholder="大胆地介绍自己" clearable />
                    </el-form-item>

                    <el-form-item prop="sex" label="性别">
                        <el-radio-group v-model="registerForm.sex" class="pl-3">
                            <el-radio value="0">女生</el-radio>
                            <el-radio value="1">男生</el-radio>
                            <el-radio value="2">保密</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item prop="birthday" label="生日">
                        <div class="inline pl-3">
                            <el-date-picker v-model="registerForm.birthday" type="date" placeholder="生日"
                                value-format="YYYY-MM-DD" :disabled-date="disabledDate" :shortcuts="shortcuts"
                                :size="size" />
                        </div>
                    </el-form-item>
                    <div class="text-sm text-center pt-3"> 注册即表示您同意并愿意遵守 <a
                            class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                            @click="router.push('/agreement')">用户协议</a> 与 <a
                            class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                            @click="router.push('/privacy')">隐私政策</a></div>
                    <el-form-item>
                        <!-- 登录按钮，宽度设置为 100% -->
                        <el-button class="w-full mt-2 dark:text-gray-100" size="large" type="primary" :loading="loading"
                            @click="userRegister">注册</el-button>
                    </el-form-item>
                    <!-- <button type="submit" @click="userLogin"
                            class="w-full text-white bg-sky-600 font-medium hover:bg-sky-700 focus:ring-4 focus:outline-none focus:ring-sky-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-sky-500 dark:hover:bg-sky-600 dark:focus:ring-sky-800">
                            登录
                        </button> -->
                    <div class="text-sm font-medium text-gray-500 dark:text-gray-300">
                        已有账户? <a @click="router.push('/user/login')"
                            class="text-blue-700 hover:underline dark:text-blue-500">登录账户</a>
                    </div>
                </el-form>
            </div>
        </div>
    </main>
</template>

<script setup>
// 引入 Element Plus 中的用户、锁图标
import { User, Lock, Checked, Avatar, Message, UserFilled, EditPen, ChatRound, Phone, Location, School, Iphone, Sugar, Edit, Reading, Collection, Link } from '@element-plus/icons-vue'
import { login } from '@/api/admin/user';
import {ref, reactive, onMounted, onBeforeUnmount} from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { showMessage } from '@/composables/utils';
import { setToken } from '@/composables/auth';
import { useUserStore } from '@/stores/user';
import { useDark, useToggle } from '@vueuse/core'
import { register } from '@/api/frontend/user';
import { uploadFile } from '@/api/frontend/file';
import { useBlogSettingsStore } from '@/stores/blogsettings';
import schools from '@/assets/ChinaUniversityList.json';
import { regionData } from 'element-china-area-data';

const size = ref("default")


const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
const userStore = useUserStore()
const router = useRouter()
const registerForm = reactive({
    username: null,
    password: null,
    nickname: null,
    mail: null,
    signature: null,
    qqId: null,
    phoneNumber: null,
    sex: null,
    birthday: null,
    localCity: null,
    university: null,
    avatar: null,
    introduce: null,
    github: null,
    gitee: null,
    personBlog: null,
    localCityCode: []
})
const blogSettingsStore = useBlogSettingsStore()
const formRef = ref(null)
//表单验证规则
const rules = {
    username: [
        {
            required: true,
            message: "用户账号不能为空！",
            trigger: "blur"
        }
    ],
    password: [
        {
            required: true,
            message: "密码不能为空！",
            trigger: "blur"
        }
    ],
    confirmPassword: [
        {
            required: true,
            message: "确认密码不能为空！",
            trigger: "blur"
        }
    ],
    mail: [
        {
            required: true,
            message: "邮箱不能为空！",
            trigger: "blur"
        }
    ],
    nickname: [
        {
            required: true,
            message: "昵称不能为空！",
            trigger: "blur"
        }
    ]
}


// 是否选择省份
const isSelectProvince = ref(false)
const schoolList = ref(schools)
// 所选择省份
const selectedProvince = ref('')
// 所选择省份的学校列表
const selectedProvinceSchools = ref([])
// 所选择学校
const selectedSchool = ref('')
// 选择省份改变，更新学校库
const handleSchoolCityChange = () => {
    let ps = schoolList.value.filter(school => school.province === selectedProvince.value)[0];
    selectedProvinceSchools.value = ps.schools;
    isSelectProvince.value = true;
    // selectedProvinceSchools.value = value;
}

// 学校搜索
const schoolQuerySearch = (queryString, cb) => {
    const results = queryString ? selectedProvinceSchools.value.filter(schoolFilter(queryString)) : selectedProvinceSchools.name;
    cb(results);
};

// 学校过滤器
const schoolFilter = (queryString) => {
    return (school) => {
        return school.name.toLowerCase().indexOf(queryString.toLowerCase())=== 0;
    }
};

// 学校选择
const handleSchoolSelect = (item) => {
    console.log(item);
    registerForm.university = item.name;
    selectedSchool.value = item.name
}

const selectedArea = ref([]); // 绑定选中的省市区编码数组
// 配置选项显示规则
const cascaderProps = {
  value: 'value',    // 选项值字段
  label: 'label',    // 选项显示字段
  children: 'children' // 子级字段
};

// 使用 Element 内置的中国省市区数据
const areaOptions = regionData;

// 城市选择变化
const handleCityChange = (value) => {
    registerForm.localCity = encodeArea(value)  
}
// 将城市编码数组转换为字符串
const encodeArea = (codes) => {
    if (codes == null || codes.length == 0) {
        return ""
    }

    // 获取城市数据库
    let cityData = areaOptions
    // 遍历编码数组，获取对应的城市名称
    let names = []
    for (const code of codes) {
        const nodeCity = cityData.find(node => node.value === code)

        if (nodeCity) {
            names.push(nodeCity.label)
            // 更新为子城市数据
            cityData = nodeCity.children || []
        } else {
            // 找不到对应的城市，返回空字符串
            names.push("")
            break
        }
    }
    // 将城市名称数组转换为字符串
    return names.join("-")
}

// 将城市逆向为编码数组
const decodeArea = (name) => {
    if (name == null || name == "") {
        return []
    }

    // 获取城市数据库
    let cityData = areaOptions
    // 将城市名称字符串转换为数组
    let names = name.split("-")
    // 遍历城市名称数组，获取对应的城市编码
    let codes = []  
    for (const name of names) {
        const nodeCity = cityData.find(node => node.label === name)

        if (nodeCity) {
            codes.push(nodeCity.value)
            // 更新为子城市数据
            cityData = nodeCity.children || []  
        }  else {
            // 找不到对应的城市，返回空数组
            break 
        }
    }

    return codes;
}
// 上传头像图片
const handleUserAvatarImg = (file) => {
    let formData = new FormData()
    //添加file字段
    formData.append('file', file.raw)
    uploadFile(formData).then((res) => {
        if (res.success == true) {
            registerForm.avatar = res.data.url
            showMessage("上传头像成功！")
        } else if(res.success == false) {
            let message = res.message
            showMessage(message, 'error')
        }
    }).catch((err) => {
        showMessage("头像上传失败或超时！请尝试减小头像资源大小(推荐2MB以内)", 'error')
    })
}

//登录加载按钮
const loading = ref(false)
// 提交注册请求
const userRegister = () => {
    //校验表单字段
    formRef.value.validate((valid) => {
        if (valid == false) {
            // 校验失败，不执行注册逻辑
            return
        }
        // 验证密码与确认密码是否一致
        if (registerForm.password !== registerForm.confirmPassword) {
            showMessage('密码与确认密码不一致！','error')
            return
        }
        // 开启加载动画
        loading.value = true

        // 发送注册请求
        register(registerForm).then((res) => {
            if (res.success == true) {
                // 注册成功，跳转到登录页面
                showMessage('注册成功！', 'success')
                router.push('/user/login')
            } else {
                // 注册失败，显示错误信息
                showMessage(res.message,'error')
            }
        }).catch((err) => {
            // 注册失败，显示错误信息
            showMessage(err.message,'error')
        }).finally(() => {
            // 关闭加载动画
            loading.value = false
        })
    })
}

// 按回车键后，执行注册事件
function onKeyUp(e) {
    console.log(e)
    if (e.key == 'Enter') {
        userRegister()
    }
}

// 添加键盘监听
onMounted(() => {
    console.log('添加键盘监听')
    document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(() => {
    document.removeEventListener('keyup', onKeyUp)
})

</script>

<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-show {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.basic {
  flex: 1;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>